package com.echo.im.mq.config;

import com.echo.im.mq.event.receiver.AbstractMessageReceiver;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * RabbitMQ 配置类，负责初始化消息监听器容器。弄成手动的原因是支持自动扫描
 * 
 * @author echo
 * @date 2024-08-15
 */
@Configuration
@RequiredArgsConstructor
public class RabbitReceiverAutoBindingConfig {

    private final ConnectionFactory connectionFactory;
    private final List<AbstractMessageReceiver<?>> receivers;
    private final ApplicationContext applicationContext;
    private final RabbitProperties rabbitProperties;

    /**
     * 在应用启动时注册消息监听器容器 Bean。
     * 遍历所有消息接收器，并为每个接收器创建和注册 SimpleMessageListenerContainer。
     */
    @PostConstruct
    public void registerBeans() {
        for (AbstractMessageReceiver<?> receiver : receivers) {
            String queueName = receiver.getQueueName();
            SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
            container.setConnectionFactory(connectionFactory);
            container.setQueueNames(queueName);
            container.setMessageListener(receiver);
            container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
            ((ConfigurableApplicationContext) applicationContext).getBeanFactory().registerSingleton(queueName, container);
        }
    }

}
